import React, {Component} from 'react'
import {connect} from 'react-redux'
import UrlPattern from 'url-pattern'
import {message, Icon, Card} from 'antd'

import OnlineCodingAnswer from './assignment/online-coding-answer'
import * as actions from '../actions/online-coding-answer'

import {studentAnswerPageUrl} from '../constant/constant-url'

class StudentAnswerPage extends Component {
  constructor () {
    super()
    this.state = {
      assignmentId: 0,
      quizId: 0
    }
  }

  componentDidMount () {
    const pattern = new UrlPattern(studentAnswerPageUrl)
    const urlParams = pattern.match(this.props.location.pathname)
    this.setState({
      paperId: urlParams.paperId,
      assignmentId: urlParams.assignmentId,
      quizId: urlParams.quizId
    })
    this.props.studentGetOnlineCodingAnswer(urlParams, this.renderErrorMessage)
  }

  renderErrorMessage () {
    return message.error('你没有权限查看答案，请先完成作业！')
  }

  getAnswerFile () {
    const { programCenterUrl } = this.props.settings
    const downloadFileUri = `${programCenterUrl}/api/v2/onlineCodingQuizzes/${this.state.quizId}/answerFile`
    window.location.assign(downloadFileUri)
  }

  render () {
    const {onlineCoding} = this.props

    return (<div>
      <Card title={<a onClick={() => window.history.back()}><Icon type='arrow-left' />返回我的作业</a>} noHovering bordered={false}>
        <OnlineCodingAnswer isStudent onlineCodingQuiz={onlineCoding} getAnswerFile={this.getAnswerFile.bind(this)} />
      </Card>
    </div>)
  }
}

const mapStateToProps = (state) => {
  return {
    user: state.user,
    onlineCoding: state.onlineCodingAnswer,
    settings: state.settings
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    studentGetOnlineCodingAnswer: (data, callback) => dispatch(actions.studentGetOnlineCodingAnswer(data, callback))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(StudentAnswerPage)
